package com.haixiaoke.saas.lock.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.lock.domain.Model;
import com.haixiaoke.saas.lock.mapper.ModelMapper;
import com.haixiaoke.saas.lock.service.IDeviceLockService;
import com.haixiaoke.saas.lock.service.IModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 型号Service业务层处理
 *
 * @author panda
 * @date 2025-04-12
 */
@Service
public class ModelServiceImpl implements IModelService {
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private IDeviceLockService deviceLockService;

    /**
     * 查询型号
     *
     * @param modelId 型号主键
     * @return 型号
     */
    @Override
    public Model selectModelByModelId(Long modelId) {
        return modelMapper.selectModelByModelId(modelId);
    }

    /**
     * 查询型号列表
     *
     * @param model 型号
     * @return 型号
     */
    @Override
    public List<Model> selectModelList(Model model) {
        return modelMapper.selectModelList(model);
    }

    /**
     * 新增型号
     *
     * @param model 型号
     * @return 结果
     */
    @Override
    public int insertModel(Model model) {
        if (StrUtil.isEmpty(model.getModelName()) || StrUtil.isEmpty(model.getBrandName())) {
            throw new ServiceException("型号名称或品牌名称不能为空");
        }
        Model sqlModel = modelMapper.selectModelByModelId(model.getModelId());
        if (ObjectUtil.isNotEmpty(sqlModel)) {
            throw new ServiceException("型号已存在");
        }
        model.setCreateTime(DateUtils.getNowDate());
        return modelMapper.insertModel(model);
    }

    /**
     * 修改型号
     *
     * @param model 型号
     * @return 结果
     */
    @Override
    public int updateModel(Model model) {
        model.setUpdateTime(DateUtils.getNowDate());
        return modelMapper.updateModel(model);
    }

    /**
     * 批量删除型号
     *
     * @param modelIds 需要删除的型号主键
     * @return 结果
     */
    @Override
    public int deleteModelByModelIds(Long[] modelIds) {
        return modelMapper.deleteModelByModelIds(modelIds);
    }

    /**
     * 删除型号信息
     *
     * @param modelId 型号主键
     * @return 结果
     */
    @Override
    public int deleteModelByModelId(Long modelId) {
        int count = deviceLockService.countDeviceLockByModelId(modelId);
        if (count > 0) {
            throw new ServiceException("该型号已被设备锁使用，不能删除");
        }
        return modelMapper.deleteModelByModelId(modelId);
    }
}
